package com.qujia.station.controller;

import com.alibaba.fastjson.JSONObject;
import com.qujia.common.constant.HttpStatus;
import com.qujia.common.constant.UserConstants;
import com.qujia.common.core.controller.BaseController;
import com.qujia.common.core.domain.AjaxResult;
import com.qujia.common.core.domain.entity.SysUser;
import com.qujia.common.core.page.PageDomain;
import com.qujia.common.core.page.TableDataInfo;
import com.qujia.common.core.page.TableSupport;
import com.qujia.common.utils.SecurityUtils;
import com.qujia.common.utils.StringUtils;
import com.qujia.common.utils.poi.ExcelUtil;
import com.qujia.station.domain.Repositories;
import com.qujia.station.service.RepositoryService;
import com.qujia.station.utils.RegexUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/repository")
@Slf4j
@Api(value = "仓库管理接口")
public class RepositoryController extends BaseController {

    @Autowired
    private RepositoryService repositoryService;

    @PostMapping("/add")
    @ApiOperation(value = "新增仓库",httpMethod = "POST")
    public AjaxResult addRepository(@RequestBody Repositories repository){
        SysUser user = SecurityUtils.getLoginUser().getUser();
        if(Objects.isNull(user)){
            return AjaxResult.error("该账号不存在，请求登录");
        }
        if(judgeAccount(user)) {
            if (Objects.isNull(repository) || StringUtils.isEmpty(repository.getStationName())) {
                return AjaxResult.error("请求参数异常");
            }

            if(repository.getStationName().length() > 50){
                return AjaxResult.error("仓库名称超出长度限制");
            }

            if(StringUtils.isNotEmpty(repository.getLeader()) && repository.getLeader().length() > 50){
                return AjaxResult.error("联系人超出长度限制");
            }
            if(StringUtils.isNotEmpty(repository.getPhone()) && !RegexUtils.isPhoneNum(repository.getPhone())){
                return AjaxResult.error("请输入正确的手机号");
            }
            if(StringUtils.isNotEmpty(repository.getDetailRegionData()) && repository.getDetailRegionData().length() > 50){
                return AjaxResult.error("地址超出长度限制");
            }
            if(StringUtils.isNotEmpty(repository.getNotes()) && repository.getNotes().length() > 200){
                return AjaxResult.error("备注超出长度限制");
            }
            repository.setCreateUser(user.getUserId());
            log.info("addRepository 新增仓库请求参数：[{}]", JSONObject.toJSONString(repository));
            int i = repositoryService.saveRepository(repository);
            log.info("addRepository 新增仓库返回结果：[{}]", i);
            if(i <= 0){
                return AjaxResult.error("新增仓库失败");
            }
            return AjaxResult.success();
        } else {
            return AjaxResult.error("该账号不能新增仓库");
        }
    }

    // 只有admin 账号可以增删改
    private boolean judgeAccount(SysUser user){
        if(UserConstants.LEVEL_ONE.equals(user.getUserLevel()) || Objects.isNull(user.getUserLevel())){
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }


    @PostMapping("/list")
    @ApiOperation(value = "查询仓库列表",httpMethod = "POST")
    public TableDataInfo selectRepositoryList(@RequestBody Repositories repository){
        if(Objects.isNull(repository) || Objects.isNull(repository.getPageNum())
                || Objects.isNull(repository.getPageSize())){
            TableDataInfo rspData = new TableDataInfo();
            rspData.setCode(HttpStatus.ERROR);
            rspData.setMsg("请求参数异常");
            rspData.setRows(null);
            rspData.setTotal(0);
            return rspData;
        }
        SysUser user = SecurityUtils.getLoginUser().getUser();
        if(Objects.isNull(user)){
            return failUserTable();
        }
        if(judgeAccount(user)) {
            PageDomain pageDomain = TableSupport.buildPageRequest();
            pageDomain.setPageNum(repository.getPageNum());
            pageDomain.setPageSize(repository.getPageSize());
            startPage(pageDomain);
            log.info("selectRepositoryList 查询仓库列表请求参数:[{}]", JSONObject.toJSONString(repository));
            List<Repositories> repositoryList = repositoryService.selectRepositoryList(repository);
            log.info("selectRepositoryList 查询仓库列表返回结果:[{}]", repositoryList.size());
            return getDataTable(repositoryList);
        }else {
            return failUserTable();
        }
    }


    @PostMapping("/update")
    @ApiOperation(value = "修改仓库",httpMethod = "POST")
    public AjaxResult updateRepository(@RequestBody Repositories repository){
        SysUser user = SecurityUtils.getLoginUser().getUser();
        if(Objects.isNull(user)){
            return AjaxResult.error("该账号不存在，请求登录");
        }
        if(judgeAccount(user)) {
            if(Objects.isNull(repository) || Objects.isNull(repository.getStationId())){
                return AjaxResult.error("请求参数异常");
            }

            log.info("updateRepository 修改仓库信息请求参数：[{}]",JSONObject.toJSONString(repository));
            int i = repositoryService.updateRepository(repository);
            log.info("updateRepository 修改仓库信息返回结果：[{}]",JSONObject.toJSONString(repository));
            if(i <= 0){
                return AjaxResult.error("修改仓库失败");
            }
            return AjaxResult.success();
        } else {
            return AjaxResult.error("该账号不能修改仓库");
        }
    }

    @GetMapping("/delete")
    @ApiOperation(value = "删除仓库",httpMethod = "GET")
    public AjaxResult deleteRepository(@RequestParam("repositoryIds") String repositoryIds){
        SysUser user = SecurityUtils.getLoginUser().getUser();
        if(Objects.isNull(user)){
            return AjaxResult.error("该账号不存在，请求登录");
        }
        if(StringUtils.isEmpty(repositoryIds)){
            return AjaxResult.error("请求参数异常");
        }
        if(judgeAccount(user)) {
            if (StringUtils.isEmpty(repositoryIds)) {
                return AjaxResult.error("请求参数异常");
            }
            String[] split = repositoryIds.split(",");
            List<Long> repositoryIdList = new ArrayList<>();
            for (String repositoryId : split) {
                repositoryIdList.add(Long.valueOf(repositoryId));
            }
            log.info("deleteRepository 请求参数：[{}]", repositoryIds);
            repositoryService.deleteRepository(repositoryIdList);
            return AjaxResult.success();
        } else {
            return AjaxResult.error("该账号不能删除仓库");
        }
    }

    @PostMapping("/export")
    @ApiOperation(value = "查询仓库列表",httpMethod = "POST")
    public AjaxResult selectRepositoryExport(@RequestBody Repositories repository){
        log.info("selectRepositoryList 查询仓库列表请求参数:[{}]",JSONObject.toJSONString(repository));
        List<Repositories> repositoryList = repositoryService.selectRepositoryList(repository);
        log.info("selectRepositoryList 查询仓库列表返回结果:[{}]",repositoryList.size());
        ExcelUtil<Repositories> util = new ExcelUtil<>(Repositories.class);
        return util.exportExcel(repositoryList,"仓库");
    }
}
